/**
 * OSS is a Open Service Container which gives the leverage of building the Desktop and Web
 * Application. * Copyright (C) 2008-2009  Ponraj Sutanthiramani
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Or5e Open Source Community
 * Navigator Bldg, ITPL, Bangalore, India.
 */

package org.or5e.api.calendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.or5e.core.BaseException;
import org.or5e.core.BaseObject;

/**
 * @author Pornaj Suthanthiramani
 */
public class JCalendarSpi extends BaseObject implements JCalendar{
    private Map<String, List<CalendarEntry>> calendarTable;
    private List<JCalenderListener> listeners = null;

    public JCalendarSpi() {
        calendarTable = new HashMap<String, List<CalendarEntry>>();
        listeners = new ArrayList<JCalenderListener>();
        Runtime.getRuntime().addShutdownHook(new Thread(new CalendarShutdownHook()));
    }
    @Override
    public String getName() {
        return "JCalendarSpi";
    }

    @Override
    public void initilizeCalendar(String calendarName) throws CalendarException {
        if(calendarTable.containsKey(calendarName)) {
            throw new CalendarException(CalendarExceptionConstants.E001);
        }
        calendarTable.put(calendarName, new LinkedList<CalendarEntry>());
    }

    @Override
    public void destroyCalendar(String calendarName) throws CalendarException {
        if(!calendarTable.containsKey(calendarName)) {
            throw new CalendarException(CalendarExceptionConstants.E002);
        }
        calendarTable.remove(calendarName);
    }

    @Override
    public void loadCalendar(String calendarName, String datafile) throws CalendarException {
        if(!calendarTable.containsKey(calendarName)) throw new CalendarException(CalendarExceptionConstants.E002);
        DataFileLoader _loader = new DataFileLoaderBuilder().buildDataFileLoader(datafile);
        List<CalendarEntry> calEntry = _loader.loadEntry();
        calendarTable.put(calendarName, calEntry);
    }

    @Override
    public void createCalendarEntry(String calendarName, CalendarEntry calendarEntry) throws CalendarException {
        List<CalendarEntry> listEntry = calendarTable.get(calendarName);
        if(listEntry == null) throw new CalendarException(CalendarExceptionConstants.E002);
        listEntry.add(calendarEntry);
    }

    @Override
    public List<CalendarEntry> retriveCalendarEntries(String calendarName, Calendar startDate, Calendar endDate) {
        List<CalendarEntry> resultantList = new ArrayList<CalendarEntry>();
        List<CalendarEntry> calEntry = calendarTable.get(calendarName);
        for (CalendarEntry calendarEntry : calEntry) {
            if(calendarEntry.getStartDateTime().after(startDate) && calendarEntry.getStartDateTime().before(endDate)) {
                resultantList.add(calendarEntry);
            }
        }
        return resultantList;
    }

    @Override
    public Iterator<CalendarEntry> getIterator(String calendarName) throws CalendarException {
        List<CalendarEntry> entry = calendarTable.get(calendarName);
        if(entry == null) throw new CalendarException(CalendarExceptionConstants.E002);
        return entry.iterator();
    }

    @Override
    public void updateCalendarEntry(String calendarName, CalendarEntry calendarEntry) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void deleteCalendarEntry(String calendarName, CalendarEntry calendarEntry) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public int deleteCalendarEntries(String calendarName, List<CalendarEntry> entries) {
        for (JCalenderListener listener : listeners) {
            listener.calendarEntryDeleted(new CalendarEvent());
        }
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void addListener(JCalenderListener listener) {
        listeners.add(listener);
    }

    @Override
    public List<CalendarEntry> retriveCalendarEntries(String calendarName, String meetingOrganizer) throws CalendarException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public class CalendarShutdownHook extends BaseObject implements Runnable {

        @Override
        public String getName() {
            return "CalendarShutdownHook";
        }

        @Override
        public void run() {
            info("*** Shutting down the Calendar API.");
            Set<String> keySet = calendarTable.keySet();
            for (String cacheTableKey : keySet) {
                try {
                    destroyCalendar(cacheTableKey);
                } catch (CalendarException ex) {
                    error("Exception occored in Calendar shutdown hook :"+ex.getMessage());
                }
            }
        }
    }
    public static void main(String[] args) throws Exception {
        JCalendar cal = new JCalendarSpi();
        cal.initilizeCalendar("Sabre");
        cal.loadCalendar("Sabre", "outlook/Calendar.xls");
        Calendar startData = Calendar.getInstance();
        Calendar endData = Calendar.getInstance();
        endData.add(Calendar.DATE, 2);
        List<CalendarEntry> retValue = cal.retriveCalendarEntries("Sabre", startData, endData);
        for (CalendarEntry calendarEntry : retValue) {
            System.out.println("====================");
            System.out.println(calendarEntry.getSubject());
            System.out.println(calendarEntry.getStartDateTime().get(Calendar.DATE)+"/"+calendarEntry.getStartDateTime().get(Calendar.MONTH)+"/"+calendarEntry.getStartDateTime().get(Calendar.YEAR));
            System.out.println("====================");
        }
    }
	@Override
	public void install() throws BaseException {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void uninstall() throws BaseException {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void start() throws BaseException {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void stop() throws BaseException {
		// TODO Auto-generated method stub
		
	}
}